package rmi.attempt2.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import rmi.attempt2.net.*;

public class Client {

	public static final void main(String[] args) throws Exception {
		final int port = 40004;
		final String hostname = "160.85.37.203";
		final String BIND_ADDRESSE = "eventHandler";
		EventHandler eh = null;
		
		ClientChatEventListener l = null;
		try {
			System.setProperty("java.rmi.server.hostname", hostname);
			Registry rmiregistry = LocateRegistry.getRegistry(hostname, port);
			eh = (EventHandler) rmiregistry.lookup(BIND_ADDRESSE);
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("Please type a name: ");
			String username = in.readLine();
			l = new ClientChatEventListener(username);
			UnicastRemoteObject.exportObject(l);
			eh.addChatEventListener(l);
			String message = "";
			do {
				message = in.readLine();
				if (!"".equals(message)) {
					eh.dispatchChatMessage(username, message);
				}
			} while (!"".equals(message));
		}catch (RemoteException e) {
			e.printStackTrace();
		} finally {
			if (eh != null && l != null) {
				eh.removeChatEventListener(l);
				UnicastRemoteObject.unexportObject(l, true);
				Thread.sleep(1000);
			}
		}
	}

}
